<template>
  <AppLayout :sidebar-collapsed="sidebarCollapsed">
    <!-- 侧边栏插槽 -->
    <template #sidebar>
      <Sidebar :collapsed="sidebarCollapsed" @toggle="sidebarCollapsed = !sidebarCollapsed">
        <!-- 导航菜单插槽 -->
        <template #navigation>
          <NavigationMenu :message-count="messages.length" :tts-enabled="ttsEnabled" :collapsed="sidebarCollapsed"
            @toggle-tts="toggleTTS" />
        </template>

        <!-- 侧边栏底部插槽 -->
        <template #footer>
          <!-- <StatusIndicator :is-streaming="isStreaming" :collapsed="sidebarCollapsed" /> -->
        </template>
      </Sidebar>
    </template>
    
    <!-- 主内容区插槽 -->
    <template #main>
      <AiChat
        :messages="messages"
        v-model:inputMessage="inputMessage"
        :isStreaming="isStreaming"
        :ttsEnabled="ttsEnabled"
        @sendMessage="sendMessage"
        @clearChat="clearChat"
        @exportChat="exportChat"
        @toggleTTS="toggleTTS"
        @handleMessageUpdated="handleMessageUpdated"  
      />
    </template>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import AppLayout from '@/components/layout/index.vue'
import Sidebar from '@/components/Sidebar/index.vue'
import NavigationMenu from '@/components/NavigationMenu/index.vue'
import ttsService from '../../services/TTSService.js'
import aiDialogueService from '../../services/AIDialogueService.js'
import exportService from '../../services/ExportService.js'
import AiChat from '@/components/AiChat/index.vue'
import {showNotification} from '@/utils/showNotification.js'
// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const isStreaming = ref(false)
const ttsEnabled = ref(true)
const sidebarCollapsed = ref(false)

// 初始化
onMounted(() => {
  // 添加欢迎消息
  const welcomeMessage = {
    id: 'welcome',
    role: 'assistant',
    content: '在这里，你讲和我对话，我将尽可能的回答你的问题',
    timestamp: Date.now()
  }
  messages.value.push(welcomeMessage)
})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isStreaming.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''
  isStreaming.value = true

  try {
    // 先添加用户消息到界面
    const userMsg = {
      id: Date.now().toString(),
      role: 'user',
      content: userMessage,
      timestamp: Date.now()
    }
    messages.value.push(userMsg)

    // 创建AI消息占位符
    const aiMsg = {
      id: (Date.now() + 1).toString(),
      role: 'assistant',
      content: '',
      timestamp: Date.now(),
      isStreaming: true
    }
    messages.value.push(aiMsg)

    // 发送消息并获取AI响应
    await aiDialogueService.sendMessage(
      userMessage,
      // 流式响应回调
      (streamMsg) => {
        // 直接更新AI消息内容
        const existingMsg = messages.value.find(msg => msg.id === aiMsg.id)
        if (existingMsg) {
          existingMsg.content = streamMsg.content
        }
      },
      // 完成回调
      async (streamMsg) => {
        isStreaming.value = false
        // 更新AI消息状态
        const existingMsg = messages.value.find(msg => msg.id === aiMsg.id)
        if (existingMsg) {
          existingMsg.isStreaming = false
          existingMsg.content = streamMsg.content
        }
        // 如果开启TTS，自动生成语音
        if (ttsEnabled.value && streamMsg.content) {
          const audioUrl = await ttsService.generateAudio(streamMsg.content, aiMsg.id);
          if (existingMsg) {
            existingMsg.audioUrl = audioUrl;
          }
        }
      }
    )
  } catch (error) {
    console.error('发送消息失败:', error)
    isStreaming.value = false
  }
}

// 处理消息更新
const handleMessageUpdated = (messageId) => {
  console.log('消息更新:', messageId)
}

// 清空对话
const clearChat = () => {
  messages.value = []
  aiDialogueService.clearHistory()
  ttsService.clearCache()
}

// 切换TTS
const toggleTTS = () => {
  ttsEnabled.value = !ttsEnabled.value
}

// 导出对话
const exportChat = async (messagesToExport, exportData) => {
  try {
    // 显示导出开始通知
    showNotification('开始导出对话...', 'info')
    // 调用导出服务
    await exportService.exportChat(messagesToExport, exportData.format, exportData.options)
    // 显示成功通知
    showNotification(`对话已成功导出为${exportService.getFormatDisplayName(exportData.format)}格式`, 'success')
  } catch (error) {
    showNotification(`导出失败: ${error.message}`, 'error')
  }
}



</script>

<style scoped>
/* @import './index.css'; */
</style>
